import { reactive } from 'vue'

export function usePasswordValidate() {
  const passwordState = reactive({
    strengthClass: 'info',
    strengthText: '',
    passwordTips: [],
  })

  // 校验密码强度
  const checkPasswordStrength = (password) => {
    let strength = 0

    // 密码长度检查
    const hasMinLength = password.length >= 8
    const hasMaxLength = password.length <= 16
    const lengthValid = hasMinLength && hasMaxLength

    // 包含大写字母
    const hasUpperCase = /[A-Z]/.test(password)

    // 包含小写字母
    const hasLowerCase = /[a-z]/.test(password)

    // 包含数字
    const hasNumber = /[0-9]/.test(password)

    // 包含特殊字符
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)

    // 更新提示信息
    passwordState.passwordTips = [
      { text: '8-16个字符', valid: lengthValid },
      { text: '包含大写字母', valid: hasUpperCase },
      { text: '包含小写字母', valid: hasLowerCase },
      { text: '包含数字', valid: hasNumber },
      { text: '包含特殊字符', valid: hasSpecialChar },
    ]

    // 计算强度
    if (hasMinLength) strength++
    if (hasUpperCase) strength++
    if (hasLowerCase) strength++
    if (hasNumber) strength++
    if (hasSpecialChar) strength++

    // 设置强度等级
    if (password.length === 0) {
      passwordState.strengthClass = ''
      passwordState.strengthText = ''
    } else if (password.length < 8) {
      passwordState.strengthClass = 'danger'
      passwordState.strengthText = '太短'
    } else if (strength <= 2) {
      passwordState.strengthClass = 'warning'
      passwordState.strengthText = '较弱'
    } else if (strength <= 3) {
      passwordState.strengthClass = 'info'
      passwordState.strengthText = '中等'
    } else {
      passwordState.strengthClass = 'success'
      passwordState.strengthText = '强'
    }
  }

  // 密码校验
  const validatePassword = (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入新密码'))
    } else if (value.length < 8) {
      callback(new Error('密码长度不能少于8位'))
    } else if (value.length > 16) {
      callback(new Error('密码长度不能超过16位'))
    } else if (!/[A-Z]/.test(value)) {
      callback(new Error('密码必须包含至少一个大写字母'))
    } else if (!/[a-z]/.test(value)) {
      callback(new Error('密码必须包含至少一个小写字母'))
    } else if (!/[0-9]/.test(value)) {
      callback(new Error('密码必须包含至少一个数字'))
    } else if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) {
      callback(new Error('密码必须包含至少一个特殊字符'))
    } else {
      callback()
    }
  }

  return {
    passwordState,
    validatePassword,
    checkPasswordStrength,
  }
}
